from sanic.views import HTTPMethodView
from sanic.response import json
import os,time
import json as jn
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
from processing.comm import sqlPaging,sqlOrder,set_status,timestamp_to_standard,AI_Spark_desk
from processing.Sql_DataFrom import ProJosn
from processing.AI_picture import main_pictrue,parser_Message,AI_upload_picture

class answersSparkDesk(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id
        html_data = request.json
        try:
            # 查询商家ai配置
            ai_sql = f"""
                select max_tokens,top_k,temperature,stream from a_ai_config where merchant_id='{user_id}' and status='normal' and ai_type='1'
            """
            ai_data = db.find_one(ai_sql)

            if ai_data:
                pass
            else:
                return json({'code': 201, 'message': "配置不存在！"})

            # 查询余额
            rechargerecord_sql = f"select residue,id from rechargerecord where openid='{openid}' and paymentStatus='1' and residue>0 and record_type='2' "
            balance = [i for i in db.find_all(rechargerecord_sql)]
            b_result = 0.00
            balance_total1 = 0
            balance_total = [i[0] + balance_total1 for i in db.find_all(rechargerecord_sql)]

            if sum(balance_total)<(len(html_data['content'])*100):
                return json({'code': 201, 'message': "AI智能点不够！"})

            for b in balance:
                b_result = b[0] - float(len(html_data['content'])*100)

                if b_result <= 0:
                    # 扣除余额

                    balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                    db.update(balance_sql_update)
                    continue
                else:

                    # 如果第一份充值余额不够扣除第二份
                    balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                    db.update(balance_sql_update)
                    break

            if ai_data[3]:
                stream = True
            else:
                stream = False

            content,data = AI_Spark_desk(html_data['content'],ai_data[0],ai_data[1],ai_data[2],stream)

            if content or data:
                AIid = int(Random_id(14, '10000', 'number'))
                sql = f"""
                    insert into ai_spark_desk(AIid,merchant_id,openid,type,content,keyword,max_tokens,top_k,temperature,phone,nickName,head_img,expend,expend_type,ip,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                """
                db.insert(sql,(
                    AIid,
                    user_id,
                    openid,
                    html_data['type'],
                    jn.dumps(content),
                    html_data['content'],
                    data['max_tokens'],
                    data['top_k'],
                    data['temperature'],
                    html_data['phone'] or '',
                    html_data['nickName'] or '',
                    html_data['head_img'],
                    float(len(html_data['content'])*100),
                    '1',
                    client_ip
                ))

                sql = """
                        insert into ai_data_all(search_content,merchant_id,AIid,openid,ai_type,picture_width,picture_height,preview,likes,recommend,cost,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                    """
                db.insert(sql,
                  (
                    html_data['content'],
                    user_id,
                   AIid,
                   openid,
                   1,
                   0,
                   0,
                   0,
                   0,
                   0,
                   float(len(html_data['content'])*100)
                   ))

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':content
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/answersSparkDesk', error))
            return json({'code': 200, 'message': "请求成功！"})
class getAnswersSparkDesk(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id

        try:

            sql = f"""
                select id,content,keyword,max_tokens,top_k,temperature,head_img,phone,nickName,ctime from ai_spark_desk where openid='{openid}' and merchant_id='{user_id}' and type='1'
            """
            sql = sqlOrder(sql,'ctime')
            sql = sqlPaging(1,5,sql)
            sql_data = db.find_all(sql)
            data = ProJosn(sql_data,sql)
            return json({'code': 200, 'message': "请求成功！", 'data': {
                'list': data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/answersSparkDesk', error))
            return json({'code': 200, 'message': "请求成功！"})
class getRechargerecordAi(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id

        try:

            # 查询余额
            sql = f"""
                 select sum(residue) from rechargerecord where merchant_id='{user_id}' and status='normal' and openid='{openid}' and paymentStatus='1' and record_type='2'
             """
            monery = db.find_one(sql)

            return json({'code': 200, 'message': "请求成功！", 'data': {
                'list': monery[0] or 0
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/answersSparkDesk', error))
            return json({'code': 200, 'message': "请求成功！"})

class searchPicture(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id
        html_data = request.json
        try:
            # 查询商家ai配置
            ai_sql = f"""
                select temperature,max_tokens,width,height,ai_APPID,ai_APISecret,ai_APIKEY,widthHeightType from a_ai_config where merchant_id='{user_id}' and status='normal' and ai_type='2'
            """
            ai_data = db.find_one(ai_sql)

            # 查询图片分组
            file_manage_sql = f"""
                select id from filemanage_group where merchant_id='{user_id}' and name='AI图片'
            """

            file_manage_id = db.find_one(file_manage_sql)
            if file_manage_id:
                pass
            else:
                return json({'code': 201, 'message': "AI图片分组不存在！"})

            if ai_data:
                pass
            else:
                return json({'code': 201, 'message': "配置不存在！"})

            # 查询余额
            rechargerecord_sql = f"select residue,id from rechargerecord where openid='{openid}' and paymentStatus='1' and residue>0 and record_type='2' "
            balance = [i for i in db.find_all(rechargerecord_sql)]
            b_result = 0.00
            balance_total1 = 0
            balance_total = [i[0] + balance_total1 for i in db.find_all(rechargerecord_sql)]

            if sum(balance_total)<(len(html_data['content'])*100):
                return json({'code': 201, 'message': "AI智能点不够！"})

            for b in balance:
                b_result = b[0] - float(len(html_data['content'])*100)

                if b_result <= 0:
                    # 扣除余额

                    balance_sql_update = f"update rechargerecord set residue=0,paymentStatus='4' where id={b[1]}"
                    db.update(balance_sql_update)
                    continue
                else:

                    # 如果第一份充值余额不够扣除第二份
                    balance_sql_update = f"update rechargerecord set residue={b_result}  where id={b[1]}"
                    db.update(balance_sql_update)
                    break

            # # 判断是否搜索过图片
            # sql_search = f"""
            #     select AIid from ai_data_all where merchant_id='{user_id}' and search_content='{html_data['content']}'
            # """
            # data_result = db.find_one(sql_search)

            # if data_result:
            #     sql_image = f"""
            #         select url from file_manage where merchant_id='{user_id}' and AIid='{data_result[0]}'
            #     """
            #
            #     sql_image_content = db.find_one(sql_image)
            #
            #
            #     return json({'code': 200, 'message': "请求成功！", 'data': {
            #         'list': sql_image_content[0]
            #     }})

            # 运行前请配置以下鉴权三要素，获取途径：https://console.xfyun.cn/services/tti
            APPID = ai_data[4]
            APISecret = ai_data[5]
            APIKEY = ai_data[6]
            if ai_data[7] == 'all':
                chima = str(html_data['chima']).split('x')
                ai_data = list(ai_data)
                ai_data[2] = int(chima[0])
                ai_data[3] = int(chima[1])

            desc = f'''{html_data['content']+html_data['pictureType']}'''

            res = main_pictrue(desc, appid=APPID, apikey=APIKEY, apisecret=APISecret, ai_data=ai_data)
            # 保存到指定位置
            savePath = parser_Message(res)

            image, AIid = AI_upload_picture(savePath, db, user_id, file_manage_id[0], openid)

            sql = """
                insert into ai_data_all(search_content,merchant_id,AIid,openid,ai_type,picture_width,picture_height,preview,likes,recommend,cost,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
            """
            db.insert(sql,
              (
               html_data['content']+html_data['pictureType'],
               user_id,
               AIid,
               openid,
               2,
               ai_data[2],
               ai_data[3],
               0,
               0,
               0,
               int(len(html_data['content'])*100)
               ))

            return json({'code': 200, 'message': "请求成功！",'data':{
                'list':image
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/c_views/searchPicture', error))
            return json({'code': 200, 'message': "请求成功！"})

class getSearchPicture(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum',1))
        pageSize = int(request.args.get('pageSize',10))
        keyword = request.args.get('keyword', '')
        try:
            # JOIN goods on goods_order.goods_id=goods.goods_id
            sql = f"""
               SELECT ai_data_all.search_content,file_manage.url,file_manage.openid,file_manage.AIid,ai_data_all.cost,ai_data_all.picture_width,ai_data_all.picture_height,
            ai_data_all.preview,ai_data_all.likes,ai_data_all.recommend,ai_data_all.ctime from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI' and recommend=1
            """
            tol = f""" SELECT COUNT(*) from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI'  and recommend=1 """
            if keyword:
                sql += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
                tol += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)

            data = ProJosn(data, [
                'search_content', 'url', 'openid', 'AIid', 'cost', 'picture_width', 'picture_height', 'preview',
                'likes', 'recommend', 'ctime'
            ], 'list')

            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list': data,
                'total': tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getSearchPicture/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class getCoupons(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id

        try:
            # 判断是否有可领取优惠券
            sql_Cs =  f"""
                select id,max_number,numbers,user_number from coupons 
                where merchant_id='{user_id}' and status='1' and (getCondition='静默发放') AND endTime > NOW()
            """
            sql_Cs_data = db.find_all(sql_Cs)
            sql_Cs_data = ProJosn(sql_Cs_data,sql_Cs)
            for i in sql_Cs_data:
                # 判断用户是否已领取过
                sql_get = f"""
                    select id from my_coupons where openid='{openid}' and merchant_id='{user_id}' and coupons_id={i['id']}
                """
                #    用户满足领取条件 判断是否还有领取数量
                sql_num = f"""
                    select id from my_coupons where merchant_id='{user_id}' and coupons_id={i['id']}
                """
                tol = len(db.find_all(sql_num))
                if len(db.find_all(sql_get)) < i['max_number'] and tol <= i['numbers']:
                    sql_insert = f'insert into my_coupons(merchant_id,openid,coupons_id,status,ctime,utime ) VALUES (%s,%s,%s,%s,now(),now())'
                    db.insert(sql_insert, (
                        user_id,
                        openid,
                        i['id'],
                        '0'
                    ))

                    sql_update = f"""
                          update coupons set user_number=%s where id=%s
                    """

                    db.update(sql_update,(tol+1,i['id']))
                else:
                    pass
                    # sql_insert = f'insert into my_coupons(merchant_id,openid,coupons_id,status,ctime,utime ) VALUES (%s,%s,%s,%s,now(),now())'
                    # db.insert(sql_insert,(
                    #     user_id,
                    #     openid,
                    #     i['id'],
                    #     '0'
                    # ))

            sql = f"""
                select coupons.item_dict,coupons.item_id,my_coupons.id,coupons.startTime,coupons.endTime,coupons.title,coupons.type,coupons.score,coupons.moneys,coupons.min_money,coupons.max_number,coupons.numbers, 
                coupons.content,coupons.item_id,coupons.getCondition,my_coupons.status
                from my_coupons join coupons on my_coupons.coupons_id=coupons.id where my_coupons.merchant_id='{user_id}' and my_coupons.openid='{openid}'
            """

            # sql = sqlOrder(sql,'ctime')
            sql = sqlPaging(1,5,sql)
            sql_data = db.find_all(sql)
            header = ['item_dict','item_id','id','startTime','date','title','type','score','reduce','money','max_number','numbers','content','item_id','getCondition','_status']
            data = ProJosn(sql_data,header,sql,'list')
            return json({'code': 200, 'message': "请求成功！", 'data': {
                'list': data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getCoupons/list', error))
            return json({'code': 200, 'message': "请求成功！"})
# 弹窗发放
class checkCoupons(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        client_ip = request.ip
        openid = request.app.ctx.openid
        user_id = request.app.ctx.user_id
        try:
            if openid == '':
                return json({'code': 200, 'message': "请求成功！", 'data': {
                    'list': []
                }})
            # 判断是否有可领取优惠券 and numbers <= user_number
            sql_Cs =  f""" 
                select image,id,title,type,score,moneys,min_money,content,businessId,ctime,status,item_id,getCondition,startTime,endTime,item_dict,max_number from coupons 
                where merchant_id='{user_id}' and status='1' and (getCondition='弹窗发放') AND endTime > NOW() 
            """
            sql_Cs_data = db.find_all(sql_Cs)
            sql_Cs_data = ProJosn(sql_Cs_data,sql_Cs)

            # 判断是否领取过
            my_sql_data = f"""
                select count(*) from my_coupons where merchant_id='{user_id}' and openid='{openid}' and coupons_id={sql_Cs_data[0]['id']}
            """
            # SUM = 0
            # for i in sql_Cs_data:
            #     if SUM == 0:
            #         my_sql_data +=f" and coupons_id={i['id']} "
            #     else:
            #         my_sql_data +=f" or coupons_id={i['id']} "

            if db.find_one(my_sql_data)[0] >= sql_Cs_data[0]['max_number']:

                return json({'code': 200, 'message': "请求成功！"})

            return json({'code': 200, 'message': "请求成功！", 'data': {
                'list': sql_Cs_data
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/checkCoupons/list', error))
            return json({'code': 200, 'message': "请求成功！"})


class getAIPictureList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
        keyword = request.args.get('keyword', '')
        types = request.args.get('types', '')
        try:
            # JOIN goods on goods_order.goods_id=goods.goods_id
            sql = f"""
               SELECT ai_data_all.id,c_users.head_img,c_users.nickName,ai_data_all.search_content,file_manage.url,file_manage.openid,file_manage.AIid,ai_data_all.cost,ai_data_all.picture_width,ai_data_all.picture_height,
            ai_data_all.preview,ai_data_all.likes,ai_data_all.recommend,ai_data_all.ctime from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid join c_users on ai_data_all.openid=c_users.openid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI'
            """


            tol = f""" SELECT COUNT(*) from file_manage join ai_data_all on file_manage.AIid=ai_data_all.AIid join c_users on ai_data_all.openid=c_users.openid 
            where file_manage.merchant_id='{user_id}' and file_manage.type='AI' """
            if keyword:
                sql += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
                tol += f" and  ai_data_all.search_content LIKE '%{keyword}%' "
            if types == '热门推荐':
                sql += f' and ai_data_all.recommend=1 '
                tol += f" and ai_data_all.recommend=1 "
            elif types == '最新图片':
                pass
            elif types == '我的图片':
                sql += f" and ai_data_all.openid='{openid}' "
                tol += f" and ai_data_all.openid='{openid}' "

            if types == '点赞最多':
                shoppingsql = sqlOrder(sql,'ai_data_all.likes','desc')
            else:
                shoppingsql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)

            data = ProJosn(data,[
                'id','head_img','nickName','search_content','url','openid','AIid','cost','picture_width','picture_height','preview','likes','recommend','ctime'
            ],'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'total':tol_data[0]
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/getAIPictureList/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class myCoupons(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 100))
        cou_status = (request.args.get('status', 0))
        keyword = request.args.get('keyword', '')
        try:
            sql = f"""
                select my_coupons.id,my_coupons.coupons_id,coupons.title,coupons.type,coupons.score,coupons.moneys,coupons.content,coupons.businessId,coupons.status,coupons.item_id,coupons.item_dict,goods_id,my_coupons.status
                from my_coupons join coupons on my_coupons.coupons_id=coupons.id where my_coupons.merchant_id='{user_id}' and my_coupons.openid='{openid}' and my_coupons.status='0'
            """

            header_data = ['id','coupons_id','title','type','score','moneys','content','businessId','c_status','item_id','item_dict','goods_id','my_status']
            data = db.find_all(sql)

            data = ProJosn(data,header_data,'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/selectLabel', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)


class selectLabel(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 100))
        ids = request.args.get('ids', '')
        try:
            sql = f"""
                select id,labelName,labelType,labelGrounpId,useType,setting,fontColor,backgroundColor,borderColor,sort,image from goods_label where merchant_id='{user_id}' and status='normal' and useType='微信小程序'
            """
            sql = sqlOrder(sql,'sort')
            sql = sqlPaging(pageNum,pageSize,sql)
            data = db.find_all(sql)
            data = ProJosn(data,sql,'sql')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/selectLabel', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)


# 签到配置
class signIn_list(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum',1))
        pageSize = int(request.args.get('pageSize',10))
        keyword = request.args.get('keyword', '')
        try:
            sql = """
               select id,title,image,sort,reward_id,content,sign_in_mode,sign_in_send,reward_type,sort,status,ctime,startTime,endTime,number_day from sign_in where merchant_id=%s
            """
            tol = f""" SELECT COUNT(*) FROM sign_in where merchant_id='{user_id}' """
            if keyword:
                sql += f" and  title LIKE '%{keyword}%' "
                tol += f" and  title LIKE '%{keyword}%' "
            shoppingsql = sqlOrder(sql,'sort','ASC')
            sql = sqlPaging(pageNum, pageSize, shoppingsql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql,(user_id))
            data = ProJosn(data, sql)

            # 已签到的数据
            alreadySql = f"""
                select id,sign_in_id,openid,user_id,status,ctime from sign_in_record where merchant_id='{user_id}' and openid='{openid}'
            """
            shoppingsql = sqlOrder(alreadySql, 'ctime', 'ASC')
            data1 = db.find_all(shoppingsql)
            print(2131231,data1)
            if data1:
                data1 = ProJosn(data1,alreadySql)
            else:
                data1 = []
            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
                'alreadyData':data1
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 判断是否今天有签到
class day_sigin_in(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        client_ip = request.ip
        try:
            sql = """
                SELECT status FROM sign_in_record WHERE DATE(ctime) = CURDATE() and merchant_id=%s and openid=%s
            """
            data = db.find_one(sql,(user_id,openid))
            # data = ProJosn(data, sql)

            if data:
                return json({'code': 200, 'message': "请求成功!",'data':{
                    'list':data[0],
                }})
            return json({'code': 200, 'message': "请求成功!", 'data': {
                'list': 0,
            }})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 判断是否今天有签到
class play_sigin_in(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        openid = request.app.ctx.openid
        sign_in_id = int(request.args.get('sign_in_id', 0))
        userId = int(request.args.get('user_id', 0))
        client_ip = request.ip
        try:
            #  找出今天签到配置时间范围
            # 1.获取当前时间   2.用时间去查询是否有该时间配置
            sql_time = f"""
                SELECT id FROM sign_in WHERE startTime<=NOW() and endTime>NOW() and status='1' and merchant_id='{user_id}'
            """

            sql_data = db.find_one(sql_time)
            if not sql_data:
                return json({'code': 202, 'message': "签到配置有问题!"})
            sql = """
                SELECT status FROM sign_in_record WHERE DATE(ctime) = CURDATE() and merchant_id=%s and openid=%s
            """
            data = db.find_all(sql,(user_id,openid))
            if data:
                return json({'code': 200, 'message': "今天已签过到!"})

            sql_sigin_in = f"""insert into sign_in_record(merchant_id,sign_in_id,openid,user_id,status,ctime ) VALUES (%s,%s,%s,%s,%s,now())"""
            db.insert(sql_sigin_in,(user_id,sql_data[0],openid,userId,'1'))

            return json({'code': 200, 'message': "签到成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/sign_in_list/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)